package com.asimplefox.controllers;

import com.asimplefox.entity.vo.RegisterVo;
import com.asimplefox.entity.vo.UserVo;
import com.asimplefox.service.abst.ResultU;
import com.asimplefox.service.stand.AuthService;
import com.asimplefox.service.stand.LoginDetailService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author github.kloping
 */
@RestController
@RequestMapping("/user")
public class AuthController implements ResultU {

    @Autowired
    LoginDetailService loginDetailService;

    @RequestMapping("/login")
    public Object login(@RequestBody UserVo userVo, HttpServletRequest request, HttpServletResponse response) {
        return loginDetailService.loginNow(userVo, request, response);
    }

    @Autowired
    AuthService authService;

    @RequestMapping("/reqvcode")
    public Object reqvcode(@RequestParam("email") String email, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (AuthService.isValidEmail(email)) {
                if (authService.requestCode(email)) {
                    return success( "ok");
                } else {
                    response.setStatus(400);
                    return fail( "请求频繁");
                }
            } else return fail( "邮箱格式不正确");
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            return error( "服务器错误");
        }
    }

    @RequestMapping("/register")
    public Object register(@RequestBody RegisterVo vo, HttpServletRequest request, HttpServletResponse response) {
        if (authService.checkCode(vo.getEmail(), vo.getCode())) {
            return authService.register(vo, request, response);
        } else {
            response.setStatus(400);
            return fail( "验证码不存在或错误");
        }
    }

    @RequestMapping("/check")
    public Object check(@RequestParam("id") String id) {
        return authService.check(id);
    }

    @RequestMapping("/logout")
    @PreAuthorize("hasAnyAuthority('user')")
    public Object logout(@AuthenticationPrincipal UserDetails userDetails, HttpServletRequest request, HttpServletResponse response) {
        return loginDetailService.logoutNow(userDetails, request, response);
    }
}
